<template>
  <div class="users-page">
    <!-- 搜索表单 -->
    <el-card class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未激活" value="inactive" />
            <el-option label="已激活" value="active" />
          </el-select>
        </el-form-item>

        <el-form-item label="搜索关键词">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入昵称或手机号"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <div class="header-actions">
            <el-button @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="头像" width="80">
          <template #default="{ row }">
            <el-avatar
              :src="row.avatar_url"
              :size="40"
            >
              {{ row.nickname?.charAt(0) || '用' }}
            </el-avatar>
          </template>
        </el-table-column>

        <el-table-column prop="nickname" label="昵称" min-width="120">
          <template #default="{ row }">
            {{ row.nickname || '未设置' }}
          </template>
        </el-table-column>

        <el-table-column prop="phone_number" label="手机号" min-width="120">
          <template #default="{ row }">
            {{ row.phone_number || '未绑定' }}
          </template>
        </el-table-column>

        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'active' ? 'success' : 'warning'"
              class="status-tag"
            >
              {{ row.status === 'active' ? '已激活' : '未激活' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="发言状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.chat_banned ? 'danger' : 'success'"
              class="status-tag"
            >
              {{ row.chat_banned ? '已禁言' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="publishing_credits" label="剩余公司发布条数" width="120" />

        <el-table-column prop="local_service_credits" label="本地服务发布次数" width="140" />

        <el-table-column label="注册时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                type="primary"
                size="small"
                @click="handleViewDetail(row)"
              >
                查看详情
              </el-button>

              <el-button
                v-if="row.status === 'inactive'"
                type="success"
                size="small"
                @click="handleActivate(row)"
              >
                激活
              </el-button>

              <el-button
                type="warning"
                size="small"
                @click="handleEditCredits(row)"
              >
                调整发布额度
              </el-button>

              <el-button
                type="info"
                size="small"
                @click="handleEditChatCredits(row)"
              >
                调整聊天次数
              </el-button>

              <el-button
                type="primary"
                size="small"
                @click="handleEditContactViewCredits(row)"
              >
                调整查看次数
              </el-button>

              <el-button
                type="primary"
                plain
                size="small"
                @click="handleEditLocalServiceCredits(row)"
              >
                调整本地服务
              </el-button>

              <el-button
                v-if="!row.chat_banned"
                type="danger"
                size="small"
                @click="handleBanChat(row)"
              >
                禁言
              </el-button>

              <el-button
                v-if="row.chat_banned"
                type="success"
                size="small"
                @click="handleUnbanChat(row)"
              >
                解禁
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="用户详情"
      width="600px"
    >
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">
            {{ currentUser.id }}
          </el-descriptions-item>
          <el-descriptions-item label="OpenID">
            {{ currentUser.openid }}
          </el-descriptions-item>
          <el-descriptions-item label="昵称">
            {{ currentUser.nickname || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ currentUser.phone_number || '未绑定' }}
          </el-descriptions-item>
          <el-descriptions-item label="微信号">
            {{ currentUser.wechat_id || '未设置' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === 'active' ? 'success' : 'warning'">
              {{ currentUser.status === 'active' ? '已激活' : '未激活' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="剩余公司发布条数">
            {{ currentUser.publishing_credits }}
          </el-descriptions-item>
          <el-descriptions-item label="剩余聊天次数">
            {{ currentUser.chat_credits }}
          </el-descriptions-item>
          <el-descriptions-item label="剩余查看次数">
            {{ currentUser.contact_view_credits }}
          </el-descriptions-item>
          <el-descriptions-item label="本地服务发布次数">
            {{ currentUser.local_service_credits }}
          </el-descriptions-item>
          <el-descriptions-item label="邀请者ID">
            {{ currentUser.inviter_id || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="注册时间">
            {{ formatDate(currentUser.created_at) }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentUser.avatar_url" class="user-avatar">
          <h4>用户头像</h4>
          <el-image
            :src="currentUser.avatar_url"
            style="width: 100px; height: 100px"
            fit="cover"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 调整发布额度对话框 -->
    <el-dialog
      v-model="creditsDialogVisible"
      title="调整公司发布额度"
      width="560px"
    >
      <el-form :model="creditsForm" label-width="140px" class="credit-form">
        <el-form-item label="当前剩余发布额度">
          <span class="credit-value">{{ publishingCredits }} 条</span>
        </el-form-item>
        <el-form-item label="请选择本次操作">
          <el-radio-group v-model="creditsForm.mode" class="mode-radio-group">
            <el-radio-button label="increase">增加</el-radio-button>
            <el-radio-button
              label="decrease"
              :disabled="!canReducePublishingCredits"
            >
              删除
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="creditsForm.mode === 'increase' ? '增加条数' : '减少条数'">
          <el-input-number
            v-model="creditsForm.amount"
            :min="1"
            :max="creditsForm.mode === 'increase' ? CREDIT_ADJUST_MAX : publishingCredits"
            :step="1"
            :disabled="creditsForm.mode === 'decrease' && !canReducePublishingCredits"
            placeholder="请输入条数（1-1000）"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="creditsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmCredits">确定</el-button>
      </template>
    </el-dialog>

    <!-- 调整聊天信用对话框 -->
    <el-dialog
      v-model="chatCreditsDialogVisible"
      title="调整聊天消息次数"
      width="560px"
    >
      <el-form :model="chatCreditsForm" label-width="140px" class="credit-form">
        <el-form-item label="当前剩余聊天次数">
          <span class="credit-value">{{ chatCredits }} 次</span>
        </el-form-item>
        <el-form-item label="请选择本次操作">
          <el-radio-group v-model="chatCreditsForm.mode" class="mode-radio-group">
            <el-radio-button label="increase">增加</el-radio-button>
            <el-radio-button
              label="decrease"
              :disabled="!canReduceChatCredits"
            >
              删除
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="chatCreditsForm.mode === 'increase' ? '增加次数' : '减少次数'">
          <el-input-number
            v-model="chatCreditsForm.amount"
            :min="1"
            :max="chatCreditsForm.mode === 'increase' ? CREDIT_ADJUST_MAX : chatCredits"
            :step="1"
            :disabled="chatCreditsForm.mode === 'decrease' && !canReduceChatCredits"
            placeholder="请输入次数（1-1000）"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="chatCreditsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmChatCredits">确定</el-button>
      </template>
    </el-dialog>

    <!-- 调整查看信用对话框 -->
    <el-dialog
      v-model="contactViewCreditsDialogVisible"
      title="调整查看联系方式次数"
      width="560px"
    >
      <el-form :model="contactViewCreditsForm" label-width="140px" class="credit-form">
        <el-form-item label="当前剩余查看次数">
          <span class="credit-value">{{ contactViewCredits }} 次</span>
        </el-form-item>
        <el-form-item label="请选择本次操作">
          <el-radio-group v-model="contactViewCreditsForm.mode" class="mode-radio-group">
            <el-radio-button label="increase">增加</el-radio-button>
            <el-radio-button
              label="decrease"
              :disabled="!canReduceContactViewCredits"
            >
              删除
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="contactViewCreditsForm.mode === 'increase' ? '增加次数' : '减少次数'">
          <el-input-number
            v-model="contactViewCreditsForm.amount"
            :min="1"
            :max="contactViewCreditsForm.mode === 'increase' ? CREDIT_ADJUST_MAX : contactViewCredits"
            :step="1"
            :disabled="contactViewCreditsForm.mode === 'decrease' && !canReduceContactViewCredits"
            placeholder="请输入次数（1-1000）"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="contactViewCreditsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmContactViewCredits">确定</el-button>
      </template>
    </el-dialog>

    <!-- 调整本地服务额度对话框 -->
    <el-dialog
      v-model="localServiceCreditsDialogVisible"
      title="调整本地服务发布额度"
      width="560px"
    >
      <el-form :model="localServiceCreditsForm" label-width="140px" class="credit-form">
        <el-form-item label="当前剩余本地服务次数">
          <span class="credit-value">{{ localServiceCredits }} 次</span>
        </el-form-item>
        <el-form-item label="请选择本次操作">
          <el-radio-group v-model="localServiceCreditsForm.mode" class="mode-radio-group">
            <el-radio-button label="increase">增加</el-radio-button>
            <el-radio-button
              label="decrease"
              :disabled="!canReduceLocalServiceCredits"
            >
              删除
            </el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="localServiceCreditsForm.mode === 'increase' ? '增加次数' : '减少次数'">
          <el-input-number
            v-model="localServiceCreditsForm.amount"
            :min="1"
            :max="localServiceCreditsForm.mode === 'increase' ? CREDIT_ADJUST_MAX : localServiceCredits"
            :step="1"
            :disabled="localServiceCreditsForm.mode === 'decrease' && !canReduceLocalServiceCredits"
            placeholder="请输入次数（1-1000）"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="localServiceCreditsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmLocalServiceCredits">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { userApi, type User, type UserListParams } from '@/api/admin'

type CreditMode = 'increase' | 'decrease'

interface CreditForm {
  mode: CreditMode
  amount: number
}

const CREDIT_ADJUST_MAX = 1000

const createCreditForm = () =>
  reactive<CreditForm>({
    mode: 'increase',
    amount: 0
  })

const resetCreditForm = (form: CreditForm) => {
  form.mode = 'increase'
  form.amount = 0
}

// 响应式数据
const loading = ref(false)
const userList = ref<User[]>([])
const detailDialogVisible = ref(false)
const creditsDialogVisible = ref(false)
const chatCreditsDialogVisible = ref(false)
const contactViewCreditsDialogVisible = ref(false)
const localServiceCreditsDialogVisible = ref(false)
const currentUser = ref<User | null>(null)

// 搜索表单
const searchForm = reactive<UserListParams>({
  status: undefined,
  search: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 修改额度表单
const creditsForm = createCreditForm()

// 修改聊天信用表单
const chatCreditsForm = createCreditForm()

// 修改查看信用表单
const contactViewCreditsForm = createCreditForm()

// 修改本地服务信用表单
const localServiceCreditsForm = createCreditForm()

// 可用额度计算
const publishingCredits = computed(() => Number(currentUser.value?.publishing_credits ?? 0))
const chatCredits = computed(() => Number(currentUser.value?.chat_credits ?? 0))
const contactViewCredits = computed(() => Number(currentUser.value?.contact_view_credits ?? 0))
const localServiceCredits = computed(() => Number(currentUser.value?.local_service_credits ?? 0))

const canReducePublishingCredits = computed(() => publishingCredits.value > 0)
const canReduceChatCredits = computed(() => chatCredits.value > 0)
const canReduceContactViewCredits = computed(() => contactViewCredits.value > 0)
const canReduceLocalServiceCredits = computed(() => localServiceCredits.value > 0)

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString()
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const params: UserListParams = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    const response = await userApi.getList(params)
    userList.value = response.data
    pagination.total = response.pagination.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

const loadUserDetail = async (userId: User['id']) => {
  const response = await userApi.getDetail(userId)
  currentUser.value = response.data
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getUserList()
}

// 重置搜索
const handleReset = () => {
  searchForm.status = undefined
  searchForm.search = ''
  pagination.page = 1
  getUserList()
}

// 刷新
const handleRefresh = () => {
  getUserList()
}

// 查看详情
const handleViewDetail = async (user: User) => {
  try {
    await loadUserDetail(user.id)
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取用户详情失败:', error)
  }
}

// 激活用户
const handleActivate = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要激活用户 "${user.nickname || user.id}" 吗？`, '确认激活', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await userApi.updateStatus(user.id, 'active')
    ElMessage.success('用户激活成功')
    getUserList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('激活用户失败:', error)
    }
  }
}

// 修改额度
const handleEditCredits = async (user: User) => {
  try {
    await loadUserDetail(user.id)
    resetCreditForm(creditsForm)
    creditsDialogVisible.value = true
  } catch (error) {
    console.error('加载用户发布额度失败:', error)
  }
}

// 确认修改额度
const handleConfirmCredits = async () => {
  if (!currentUser.value) return

  try {
    if (creditsForm.amount <= 0) {
      ElMessage.warning('请输入本次需要调整的条数')
      return
    }

    if (creditsForm.mode === 'increase') {
      await userApi.updateCredits(currentUser.value.id, creditsForm.amount)
      ElMessage.success('额度增加成功')
    } else {
      if (!canReducePublishingCredits.value) {
        ElMessage.warning('当前剩余条数为 0，无法扣减')
        return
      }
      if (creditsForm.amount > publishingCredits.value) {
        ElMessage.warning(`最多可扣减 ${publishingCredits.value} 条（等于剩余额度）`)
        return
      }
      await userApi.reduceCredits(currentUser.value.id, creditsForm.amount)
      ElMessage.success('额度删除成功')
    }

    creditsDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('修改额度失败:', error)
  }
}

// 修改聊天信用
const handleEditChatCredits = async (user: User) => {
  try {
    await loadUserDetail(user.id)
    resetCreditForm(chatCreditsForm)
    chatCreditsDialogVisible.value = true
  } catch (error) {
    console.error('加载用户聊天信用失败:', error)
  }
}

// 确认修改聊天信用
const handleConfirmChatCredits = async () => {
  if (!currentUser.value) return

  try {
    if (chatCreditsForm.amount <= 0) {
      ElMessage.warning('请输入本次需要调整的次数')
      return
    }

    if (chatCreditsForm.mode === 'increase') {
      await userApi.updateChatCredits(currentUser.value.id, chatCreditsForm.amount)
      ElMessage.success('聊天信用增加成功')
    } else {
      if (!canReduceChatCredits.value) {
        ElMessage.warning('当前剩余次数为 0，无法扣减')
        return
      }
      if (chatCreditsForm.amount > chatCredits.value) {
        ElMessage.warning(`最多可扣减 ${chatCredits.value} 次（等于剩余次数）`)
        return
      }
      await userApi.reduceChatCredits(currentUser.value.id, chatCreditsForm.amount)
      ElMessage.success('聊天信用删除成功')
    }

    chatCreditsDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('修改聊天信用失败:', error)
  }
}

// 修改查看信用
const handleEditContactViewCredits = async (user: User) => {
  try {
    await loadUserDetail(user.id)
    resetCreditForm(contactViewCreditsForm)
    contactViewCreditsDialogVisible.value = true
  } catch (error) {
    console.error('加载用户查看信用失败:', error)
  }
}

// 确认修改查看信用
const handleConfirmContactViewCredits = async () => {
  if (!currentUser.value) return

  try {
    if (contactViewCreditsForm.amount <= 0) {
      ElMessage.warning('请输入本次需要调整的次数')
      return
    }

    if (contactViewCreditsForm.mode === 'increase') {
      await userApi.updateContactViewCredits(currentUser.value.id, contactViewCreditsForm.amount)
      ElMessage.success('查看信用增加成功')
    } else {
      if (!canReduceContactViewCredits.value) {
        ElMessage.warning('当前剩余次数为 0，无法扣减')
        return
      }
      if (contactViewCreditsForm.amount > contactViewCredits.value) {
        ElMessage.warning(`最多可扣减 ${contactViewCredits.value} 次（等于剩余次数）`)
        return
      }
      await userApi.reduceContactViewCredits(currentUser.value.id, contactViewCreditsForm.amount)
      ElMessage.success('查看信用删除成功')
    }

    contactViewCreditsDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('修改查看信用失败:', error)
  }
}

// 修改本地服务信用
const handleEditLocalServiceCredits = async (user: User) => {
  try {
    await loadUserDetail(user.id)
    resetCreditForm(localServiceCreditsForm)
    localServiceCreditsDialogVisible.value = true
  } catch (error) {
    console.error('加载用户本地服务信用失败:', error)
  }
}

// 确认修改本地服务信用
const handleConfirmLocalServiceCredits = async () => {
  if (!currentUser.value) return

  try {
    if (localServiceCreditsForm.amount <= 0) {
      ElMessage.warning('请输入本次需要调整的次数')
      return
    }

    if (localServiceCreditsForm.mode === 'increase') {
      await userApi.updateLocalServiceCredits(currentUser.value.id, localServiceCreditsForm.amount)
      ElMessage.success('本地服务额度增加成功')
    } else {
      if (!canReduceLocalServiceCredits.value) {
        ElMessage.warning('当前剩余次数为 0，无法扣减')
        return
      }
      if (localServiceCreditsForm.amount > localServiceCredits.value) {
        ElMessage.warning(`最多可扣减 ${localServiceCredits.value} 次（等于剩余次数）`)
        return
      }
      await userApi.reduceLocalServiceCredits(currentUser.value.id, localServiceCreditsForm.amount)
      ElMessage.success('本地服务额度删除成功')
    }

    localServiceCreditsDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('修改本地服务信用失败:', error)
  }
}

// 禁言用户
const handleBanChat = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要禁言用户 "${user.nickname || user.id}" 吗？`, '确认禁言', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await userApi.banChat(user.id)
    ElMessage.success('用户禁言成功')
    getUserList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('禁言用户失败:', error)
    }
  }
}

// 解除禁言
const handleUnbanChat = async (user: User) => {
  try {
    await ElMessageBox.confirm(`确定要解除用户 "${user.nickname || user.id}" 的禁言吗？`, '确认解禁', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await userApi.unbanChat(user.id)
    ElMessage.success('解除禁言成功')
    getUserList()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('解除禁言失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getUserList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  getUserList()
}

// 初始化
onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.user-detail {
  padding: 20px 0;
}

.user-avatar {
  margin-top: 20px;
  text-align: center;
}

.user-avatar h4 {
  margin-bottom: 10px;
  color: #303133;
}

.status-tag {
  margin-right: 5px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  align-items: center;
}

.action-buttons .el-button {
  margin: 0;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

/* 额度调整对话框样式 */
.credit-form {
  padding: 10px 0;
}

.credit-form .el-form-item {
  margin-bottom: 24px;
}

.credit-value {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.mode-radio-group {
  display: inline-flex;
}

.mode-radio-group :deep(.el-radio-button__inner) {
  padding: 8px 20px;
}

.credit-form :deep(.el-input-number) {
  width: 100%;
}

.credit-form :deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

@media (max-width: 768px) {
  .users-page {
    padding: 15px;
  }

  .el-table {
    font-size: 12px;
  }

  .el-pagination {
    text-align: center;
  }

  .action-buttons {
    gap: 4px;
  }

  .action-buttons .el-button {
    font-size: 11px;
    padding: 4px 8px;
  }
}
</style>
